<template>
  <div v-loading="loading">
    <div class="panel">
      <div class="panel-header">商户主体信息</div>
      <i-form
        class="import-form"
        ref="merchantForm"
        :default-span="12"
        :items="merchantFormItems"
        :model="merchantForm"
        :rules="merchantRules"
        :inline="true"
        :label-width="200"
      >
        <!-- <template slot="merchantAddress">
          <el-form-item label="门店所在地" prop="area">
            <HycAddressCascader ref="area" v-model="merchantForm.area" />
          </el-form-item>
        </template> -->
      </i-form>
    </div>
    <div class="panel">
      <div class="panel-header">结算账户信息</div>
      <i-form
        ref="accountForm"
        class="import-form"
        :default-span="12"
        :items="accountFormItems"
        :model="accountForm"
        :rules="accountRules"
        :inline="true"
        :label-width="200"
      >
        <template slot="identifyDate">
          <el-form-item prop="identifyDate" label="身份证有效期">
            <SearchDatePicker
              v-if="accountForm.periodType === '短期'"
              :start.sync="accountForm.id_card_valid_time"
              :end.sync="accountForm.id_card_valid_time2"
            />
            <div v-else class="wx_pay_datepicker">
              <el-date-picker
                v-model="accountForm.id_card_valid_time"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
              <span>——</span>
              <span>无限</span>
            </div>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel">
      <div class="panel-header">资料上传</div>
      <i-form
        ref="uploadForm"
        class="import-form"
        :default-span="12"
        :items="uploadFormItems"
        :model="uploadForm"
        :rules="uploadRules"
        :inline="true"
        :label-width="200"
      >
        <template slot="idCardCopy">
          <el-form-item label="身份证人像面照片:" prop="id_card_copy">
            <hyc-form-upload
              ref="stationImg"
              v-model="uploadForm.id_card_copy"
              :upload-data="stationImgData"
              :uploadUrl="uploadUrl"
              :isWxUpload="true"
              show-cropper
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
        <template slot="idCardNational">
          <el-form-item
            label="身份证国徽面照片:"
            prop="id_card_national"
            required
          >
            <hyc-form-upload
              ref="stationImg"
              v-model="uploadForm.id_card_national"
              :upload-data="stationImgData"
              :uploadUrl="uploadUrl"
              :isWxUpload="true"
              show-cropper
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
        <template slot="storeEntrancePic">
          <el-form-item label="充电站照片1:" prop="store_entrance_pic">
            <hyc-form-upload
              ref="stationImg"
              v-model="uploadForm.store_entrance_pic"
              :upload-data="stationImgData"
              :uploadUrl="uploadUrl"
              :isWxUpload="true"
              show-cropper
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
        <template slot="indoorPic">
          <el-form-item label="充电站照片2:" prop="indoor_pic">
            <hyc-form-upload
              ref="stationImg"
              v-model="uploadForm.indoor_pic"
              :upload-data="stationImgData"
              :uploadUrl="uploadUrl"
              :isWxUpload="true"
              show-cropper
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel-btn-wrapper">
      <el-button type="primary" @click="handleSubmit">提交保存</el-button>
    </div>
  </div>
</template>
<script>
import formValidate from '@/utils/validate'
import SearchDatePicker from '@/components/SearchDatePicker'
import HycFormUpload from '@/components/hycFormUpload'
import cityData from '@/assets/json/cityData.json'
import { applymentMicroSubmit } from '@/api/mySelf'
import { applymentMicroSubmit as merchantSubmit } from '@/api/user'
import { isObject } from 'lodash'
import dayjs from 'dayjs'

export default {
  name: 'UserWxPay',
  components: { SearchDatePicker, HycFormUpload },
  mounted() {
    if (this.$route.name === 'MyselfWxPay') {
      this.stationImgData = {
        submitUserId: this.$store.getters.userId,
      }
      this.uploadUrl =
        '/myInformation-management/basicInformation-management/micro-merchant-applyment/uploadmedia'
    } else {
      this.stationImgData = {
        submitUserId: this.$route.params.id,
      }
      this.uploadUrl =
        '/user-management/merchant-management/micro-merchant-applyment/uploadmedia'
    }
    let options = this.generateJsonToSelectOptions()
    this.changeItem(this.merchantFormItems, 'store_address_code', {
      options,
    })
    this.changeItem(this.accountFormItems, 'bank_address_code', {
      options,
    })
  },
  methods: {
    changeItem(target, targetItemValue, options = {}) {
      if (Array.isArray(target)) {
        let index = target.findIndex((item) => item.value === targetItemValue)

        if (index < 0) return

        this.$set(target, index, {
          ...target[index],
          ...options,
        })
      } else if (isObject(target)) {
        // if (!target.hasOwnProperty(targetItemValue)) return
        if (!Object.prototype.hasOwnProperty.call(target, targetItemValue))
          return

        this.$set(target, targetItemValue, {
          ...target[targetItemValue],
          ...options,
        })
      }
    },
    gaugeDistrictLevel(item) {
      if (item.y !== null) {
        return 'district'
      } else if (item.c !== null) {
        return 'city'
      } else {
        return 'province'
      }
    },
    generateJsonToSelectOptions() {
      let result = []

      let dataSource = cityData.data
      if (!Array.isArray(dataSource)) return

      dataSource.forEach((item) => {
        if (this.gaugeDistrictLevel(item) === 'province') {
          let tempItem = {
            label: item.p,
            value: item.id,
            children: [],
          }

          result.push(tempItem)
        } else if (this.gaugeDistrictLevel(item) === 'city') {
          let tempItem = {
            label: item.c,
            value: item.id,
            children: [],
          }

          let index = result.findIndex((iter) => iter.label === item.p)
          if (index < 0) return
          result[index].children.push(tempItem)
        } else if (this.gaugeDistrictLevel(item) == 'district') {
          let tempItem = {
            label: item.y,
            value: item.id,
          }

          let pindex = result.findIndex((iter) => iter.label === item.p)
          if (pindex < 0) return
          let cindex = result[pindex].children.findIndex(
            (iter) => iter.label === item.c
          )
          if (cindex < 0) return

          result[pindex].children[cindex].children.push(tempItem)
        }
      })

      return result
    },
    changeItems(target, targetItemValue, attr, attrNewVal) {
      if (!Array.isArray(target)) return

      let index = target.findIndex((item) => item.value === targetItemValue)

      if (index < 0) return

      this.$set(target, index, {
        ...target[index],
        [attr]: attrNewVal,
      })
    },
    handleSubmit() {
      let merchantFormValid = false
      let accountFormValid = false
      let uploadValid = false
      // let merchantFormValid = true
      // let accountFormValid = true
      // let uploadValid = true

      let handler = () => {}

      let submitUserId = ''
      let backUrl = ''

      if (this.$route.name === 'MyselfWxPay') {
        handler = applymentMicroSubmit
        submitUserId = this.$store.getters.userId
        backUrl = '/myself/info'
      } else {
        submitUserId = this.$route.params.id
        handler = merchantSubmit
        backUrl = `/user/detail/${submitUserId}`
      }

      this.$refs.merchantForm.validate((valid) => {
        if (valid) merchantFormValid = true
      })

      this.$refs.accountForm.validate((valid) => {
        if (valid) accountFormValid = true
      })

      this.$refs.uploadForm.validate((valid) => {
        if (valid) uploadValid = true
      })

      if (merchantFormValid && accountFormValid && uploadValid) {
        let params = {
          ...this.merchantForm,
          ...this.accountForm,
          ...this.uploadForm,
        }

        if (params.periodType === '短期') {
          params.id_card_valid_time =
            '["' +
            dayjs(params.id_card_valid_time).format('YYYY-MM-DD') +
            '","' +
            dayjs(params.id_card_valid_time2).format('YYYY-MM-DD') +
            '"]'
        } else {
          params.id_card_valid_time =
            '["' +
            dayjs(params.id_card_valid_time).format('YYYY-MM-DD') +
            '","长期"]'
        }

        if (params.id_card_valid_time2) delete params.id_card_valid_time2

        params.bank_address_code = params.bank_address_code.pop()
        params.store_address_code = params.store_address_code.pop()

        params.submitUserId = submitUserId

        this.loading = true

        handler(params)
          .then(() => {
            this.$message({
              showClose: true,
              message: '提交成功！',
              type: 'success',
            })

            this.$router.push(backUrl)
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.$message({
          showClose: true,
          message: '请根据提示完善信息！',
          type: 'warning',
        })
      }
    },
  },
  watch: {
    'accountForm.account_bank': {
      handler(val) {
        if (val === '其他银行') {
          // this.changeItems(this.accountFormItems, 'bank_name', 'required', true)
          this.accountRules['bank_name'] = [
            { required: true, message: '若选择其他银行，此项必填' },
          ]

          let index = this.accountFormItems.findIndex((item) => {
            return item.value === 'bank_name'
          })

          if (index < 0) return
          this.$set(this.accountFormItems, index, {
            ...this.accountFormItems[index],
            hidden: false,
          })
        } else {
          // this.changeItems(this.accountFormItems, 'bank_name', 'required', false)
          this.accountRules['bank_name'] = []

          let index = this.accountFormItems.findIndex((item) => {
            return item.value === 'bank_name'
          })

          if (index < 0) return
          this.$set(this.accountFormItems, index, {
            ...this.accountFormItems[index],
            hidden: true,
          })
        }
      },
      immediate: true,
    },
    'accountForm.periodType': {
      handler(val) {
        console.log(val)
        if (val === '短期') {
          this.$set(this.accountRules, 'identifyDate', [
            {
              validator: (rule, value, callback) => {
                if (
                  !this.accountForm.id_card_valid_time ||
                  this.accountForm.id_card_valid_time === '' ||
                  !this.accountForm.id_card_valid_time2 ||
                  this.accountForm.id_card_valid_time2 === ''
                ) {
                  callback(new Error('必须选择开始和结束时间'))
                } else {
                  callback()
                }
              },
            },
          ])
        } else {
          this.$set(this.accountRules, 'identifyDate', [
            {
              validator: (rule, value, callback) => {
                if (
                  !this.accountForm.id_card_valid_time ||
                  this.accountForm.id_card_valid_time === ''
                ) {
                  callback(new Error('请选择开始日期'))
                } else {
                  callback()
                }
              },
            },
          ])
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      loading: false,
      stationImgData: { submitUserId: -1 },
      uploadUrl: '',
      merchantFormItems: [
        {
          label: '门店名称',
          required: true,
          type: 'text',
          value: 'store_name',
          clearable: true,
          maxlength: 50,
          'show-word-limit': true,
        },
        {
          label: '门店所在地',
          required: true,
          type: 'cascader',
          value: 'store_address_code',
          clearable: true,
          change: () => {},
          options: [],
          placeholder: '请选择门店所在地',
          props: {
            expandTrigger: 'hover',
          },
        },
        {
          label: '门店地址',
          required: true,
          type: 'text',
          maxlength: 500,
          value: 'store_street',
          clearable: true,
          'show-word-limit': true,
        },
        {
          label: '商户简称',
          required: true,
          type: 'text',
          value: 'merchant_shortname',
          clearable: true,
          maxlength: 16,
          'show-word-limit': true,
        },
        {
          label: '联系人姓名',
          required: true,
          type: 'text',
          value: 'contact',
          clearable: true,
          maxlength: 16,
          'show-word-limit': true,
        },
        {
          label: '手机号码',
          required: true,
          type: 'text',
          value: 'contact_phone',
          clearable: true,
        },
        {
          label: '客服电话',
          required: true,
          type: 'text',
          value: 'service_phone',
          clearable: true,
        },
        {
          label: '邮箱',
          required: true,
          type: 'text',
          value: 'contact_email',
          clearable: true,
        },
      ],
      accountFormItems: [
        {
          label: '身份证姓名',
          required: true,
          type: 'text',
          value: 'id_card_name',
          clearable: true,
          maxlength: 64,
          'show-word-limit': true,
        },
        {
          label: '身份证号码',
          required: true,
          type: 'text',
          value: 'id_card_number',
          clearable: true,
          maxlength: 18,
          'show-word-limit': true,
        },
        {
          label: '身份证有效期类型',
          required: true,
          clearable: true,
          type: 'radio',
          options: [
            {
              label: '短期',
              text: '短期',
            },
            {
              label: '长期',
              text: '长期',
            },
          ],
          value: 'periodType',
        },
        {
          slot: 'identifyDate',
        },
        {
          label: '开户人姓名',
          required: true,
          type: 'text',
          value: 'account_name',
          clearable: true,
          maxlength: 50,
          'show-word-limit': true,
        },
        {
          label: '开户银行',
          required: true,
          type: 'select',
          value: 'account_bank',
          clearable: true,
          options: [
            { label: '工商银行', value: '工商银行' },
            { label: '交通银行', value: '交通银行' },
            { label: '招商银行', value: '招商银行' },
            { label: '民生银行', value: '民生银行' },
            { label: '中信银行', value: '中信银行' },
            { label: '浦发银行', value: '浦发银行' },
            { label: '兴业银行', value: '兴业银行' },
            { label: '光大银行', value: '光大银行' },
            { label: '广发银行', value: '广发银行' },
            { label: '平安银行', value: '平安银行' },
            { label: '北京银行', value: '北京银行' },
            { label: '华夏银行', value: '华夏银行' },
            { label: '农业银行', value: '农业银行' },
            { label: '建设银行', value: '建设银行' },
            { label: '邮政储蓄银行', value: '邮政储蓄银行' },
            { label: '中国银行', value: '中国银行' },
            { label: '宁波银行', value: '宁波银行' },
            { label: '其他银行', value: '其他银行' },
          ],
        },
        {
          label: '开户银行地址',
          required: true,
          type: 'cascader',
          value: 'bank_address_code',
          clearable: true,
          options: [],
          change: () => {},
          placeholder: '请选择开户银行地址',
          props: {
            expandTrigger: 'hover',
          },
        },
        {
          label: '开户银行全称（含支行）',
          type: 'text',
          value: 'bank_name',
          clearable: true,
          maxlength: 256,
          'show-word-limit': true,
          hidden: true,
        },
        {
          label: '银行账号',
          required: true,
          type: 'text',
          value: 'account_number',
          clearable: true,
          maxlength: 50,
          'show-word-limit': true,
        },
      ],
      uploadFormItems: [
        {
          slot: 'idCardCopy',
        },
        {
          slot: 'idCardNational',
        },
        {
          slot: 'storeEntrancePic',
        },
        {
          slot: 'indoorPic',
        },
      ],
      merchantForm: {},
      accountForm: {
        identifyDate: 'defualt',
        periodType: '短期',
      },
      uploadForm: {},
      merchantRules: {
        store_address_code: [{ required: true, message: '此项必填' }],
        merchant_shortname: [
          {
            validator: formValidate('validateMerchantShortName'),
          },
        ],
        contact_phone: [
          {
            validator: formValidate('validateMobile'),
          },
        ],
        service_phone: [
          {
            validator: formValidate('validateServiceMobile'),
          },
        ],
        contact_email: [
          {
            validator: formValidate('validateEmail'),
          },
        ],
      },
      accountRules: {
        id_card_number: [
          {
            validator: formValidate('validateIdCard'),
          },
        ],
        identifyDate: [
          {
            validator: (rule, value, callback) => {
              if (
                !this.accountForm.id_card_valid_time ||
                this.accountForm.id_card_valid_time === '' ||
                !this.accountForm.id_card_valid_time2 ||
                this.accountForm.id_card_valid_time2 === ''
              ) {
                callback(new Error('必须选择开始和结束时间'))
              } else {
                callback()
              }
            },
          },
        ],
        bank_address_code: [{ required: true, message: '此项必填' }],
        bank_name: [],
      },
      uploadRules: {
        id_card_copy: [{ required: true, message: '请上传身份证正面' }],
        id_card_national: [{ required: true, message: '请上传身份证背面' }],
        store_entrance_pic: [{ required: true, message: '请上传充电站照片' }],
        indoor_pic: [{ required: true, message: '请上传充电站照片' }],
      },
    }
  },
}
</script>
<style lang="scss" scoped>
.import-form {
  padding-right: 200px;
}

.wx_pay_datepicker {
  display: flex;

  .el-input {
    width: 50% !important;
  }
}
</style>
